#include "global.h"
#include "pathgroups.h"
#include "dcolordialog.h"
#include "staticfunctions.h"
#include "propertyeditor.h"

int PathGroups::count() { return m_paths.count(); }

PathGroups::PathGroups()
{
  m_sameForAll = true;
  m_paths.clear();
}

PathGroups::~PathGroups()
{
  clear();
}
void 
PathGroups::clear()
{
  for(int i=0; i<m_paths.count(); i++)
    m_paths[i]->disconnect();

  for(int i=0; i<m_paths.count(); i++)
    m_paths[i]->removeFromMouseGrabberPool();

  for(int i=0; i<m_paths.count(); i++)
    delete m_paths[i];

  m_paths.clear();
}

bool
PathGroups::isInMouseGrabberPool(int i)
{
  if (i < m_paths.count())
    return m_paths[i]->isInMouseGrabberPool();
  else
    return false;
}
void
PathGroups::addInMouseGrabberPool(int i)
{
  if (i < m_paths.count())
    m_paths[i]->addInMouseGrabberPool();
}
void
PathGroups::addInMouseGrabberPool()
{
  for(int i=0; i<m_paths.count(); i++)
    m_paths[i]->addInMouseGrabberPool();
}
void
PathGroups::removeFromMouseGrabberPool(int i)
{
  if (i < m_paths.count())
    m_paths[i]->removeFromMouseGrabberPool();
}

void
PathGroups::removeFromMouseGrabberPool()
{
  for(int i=0; i<m_paths.count(); i++)
    m_paths[i]->removeFromMouseGrabberPool();
}


bool
PathGroups::grabsMouse()
{
  for(int i=0; i<m_paths.count(); i++)
    {
      if (m_paths[i]->grabsMouse())
	return true;
    }
  return false;
}


void
PathGroups::addPath(QList<Vec> pts)
{
  PathGroupGrabber *pg = new PathGroupGrabber();
  pg->setPoints(pts);
  m_paths.append(pg);

  makePathConnections();
}

void
PathGroups::addPath(PathGroupObject po)
{
  PathGroupGrabber *pg = new PathGroupGrabber();
  pg->set(po);
  m_paths.append(pg);

  makePathConnections();
}

bool
PathGroups::checkForMultiplePaths(QString flnm)
{
  int npaths = 0;

  QFile fpath(flnm);
  fpath.open(QFile::ReadOnly);
  QTextStream fd(&fpath);
  while (! fd.atEnd())
    {
      QString line = fd.readLine();
      QStringList list = line.split(" ", QString::SkipEmptyParts);
      if (list.count() == 1)
	{	  
	  int npts = list[0].toInt();
	  if (npts > 0) npaths ++;

	  if (npaths > 1)
	    return true;

	  for(int i=0; i<npts; i++)
	    {
	      if (fd.atEnd())
		break;
	      else
		fd.readLine();
	    }
	}
    }
  
  return (npaths > 1);
}

void
PathGroups::addPath(QString flnm)
{
  PathGroupGrabber *pg = new PathGroupGrabber();

  QFile fpath(flnm);
  fpath.open(QFile::ReadOnly);
  QTextStream fd(&fpath);
  while (! fd.atEnd())
    {
      QString line = fd.readLine();
      QStringList list = line.split(" ", QString::SkipEmptyParts);
      if (list.count() == 1)
	{
	  int npts = list[0].toInt();
	  QList<Vec> pts;
	  for(int i=0; i<npts; i++)
	    {
	      if (fd.atEnd())
		break;
	      else
		{
		  QString line = fd.readLine();
		  QStringList list = line.split(" ", QString::SkipEmptyParts);		  
		  if (list.count() == 3)
		    {
		      float x = list[0].toFloat();
		      float y = list[1].toFloat();
		      float z = list[2].toFloat();
		      pts.append(Vec(x,y,z));
		    }
		}
	    }

	  if (pts.count() > 0)
	    pg->addPoints(pts);		  
	}
    }

  m_paths.append(pg);
  
  makePathConnections();
}

QList<PathGroupObject>
PathGroups::paths()
{
  QList<PathGroupObject> po;
  for(int i=0; i<m_paths.count(); i++)
    po.append(m_paths[i]->get());

  return po;
}

void
PathGroups::setPaths(QList<PathGroupObject> po)
{
  clear();

  for(int i=0; i<po.count(); i++)
    {
      PathGroupGrabber *pg = new PathGroupGrabber();
      pg->set(po[i]);
      m_paths.append(pg);
    }

  makePathConnections();
}

void
PathGroups::updateScaling()
{
  for(int i=0; i<m_paths.count();i++)
    m_paths[i]->computePathLength();
}

void
PathGroups::draw(QGLViewer *viewer, bool backToFront, Vec lightVec)
{
  for(int i=0; i<m_paths.count();i++)
    m_paths[i]->draw(viewer,
		     m_paths[i]->grabsMouse(),
		     backToFront,
		     lightVec);
}

void
PathGroups::postdraw(QGLViewer *viewer)
{
  for(int i=0; i<m_paths.count();i++)
    {
      int x,y;
      m_paths[i]->mousePosition(x,y);
      m_paths[i]->postdraw(viewer,
			   x, y,
			   m_paths[i]->grabsMouse());
    }
}

bool
PathGroups::keyPressEvent(QKeyEvent *event)
{
  for(int i=0; i<m_paths.count(); i++)
    {
      if (m_paths[i]->grabsMouse())
	{
	  if (event->key() == Qt::Key_C)
	    {
	      bool b = m_paths[i]->closed();
	      m_paths[i]->setClosed(!b);
	      return true;
	    }
	  else if (event->key() == Qt::Key_P)
	    {
	      bool b = m_paths[i]->showPoints();
	      m_paths[i]->setShowPoints(!b);    
	      return true;
	    }
	  else if (event->key() == Qt::Key_L)
	    {
	      bool b = m_paths[i]->showLength();
	      m_paths[i]->setShowLength(!b);    
	      return true;
	    }
	  else if (event->key() == Qt::Key_X)
	    {
	      m_paths[i]->setMoveAxis(PathGroupGrabber::MoveX);
	      return true;
	    }
	  else if (event->key() == Qt::Key_Y)
	    {
	      if (event->modifiers() & Qt::ControlModifier)
		m_paths[i]->redo();
	      else
		m_paths[i]->setMoveAxis(PathGroupGrabber::MoveY);
	      return true;
	    }
	  else if (event->key() == Qt::Key_Z)
	    {
	      if (event->modifiers() & Qt::ControlModifier)
		m_paths[i]->undo();
	      else
		m_paths[i]->setMoveAxis(PathGroupGrabber::MoveZ);
	      return true;
	    }
	  else if (event->key() == Qt::Key_W)
	    {
	      m_paths[i]->setMoveAxis(PathGroupGrabber::MoveAll);
	      return true;
	    }
	  else if (event->key() == Qt::Key_S)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float radx = m_paths[i]->getRadX(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    radx--;
		  else
		    radx++;
		  radx = qMax(1.0f, radx);
		  m_paths[i]->setRadX(idx, radx, m_sameForAll);
		  return true;
		}
	    }
	  else if (event->key() == Qt::Key_T)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float rady = m_paths[i]->getRadY(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    rady--;
		  else
		    rady++;
		  rady = qMax(1.0f, rady);
		  m_paths[i]->setRadY(idx, rady, m_sameForAll);
		}
	      else // switch to tube mode
		{
		  if (event->modifiers() & Qt::ShiftModifier)
		    {
		      m_paths[i]->loadCaption();
		    }
		  else
		    {
		      bool b = m_paths[i]->tube();
		      m_paths[i]->setTube(!b);
		    }
		}

	      return true;
	    }
	  else if (event->key() == Qt::Key_A)
	    {
	      int idx = m_paths[i]->pointPressed();
	      if (idx > -1)
		{
		  float a = m_paths[i]->getAngle(idx);
		  if (event->modifiers() & Qt::ShiftModifier)
		    a--;
		  else
		    a++;
		  m_paths[i]->setAngle(idx, a, m_sameForAll);
		  return true;
		}
	    }
	  else if (event->key() == Qt::Key_Delete)
	    {
	      m_paths[i]->removeFromMouseGrabberPool();
	      m_paths.removeAt(i);
	      return true;
	    }

	  if (event->key() == Qt::Key_Space)
	    {
	      PropertyEditor propertyEditor;
	      QMap<QString, QVariantList> plist;

	      QVariantList vlist;

	      vlist.clear();
	      vlist << QVariant("double");
	      vlist << QVariant(m_paths[i]->opacity());
	      vlist << QVariant(0.0);
	      vlist << QVariant(1.0);
	      vlist << QVariant(0.1); // singlestep
	      vlist << QVariant(1); // decimals
	      plist["opacity"] = vlist;

	      vlist.clear();
	      vlist << QVariant("color");
	      Vec pcolor = m_paths[i]->color();
	      QColor dcolor = QColor::fromRgbF(pcolor.x,
					       pcolor.y,
					       pcolor.z);
	      vlist << dcolor;
	      plist["color"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->segments());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["smoothness"] = vlist;

	      vlist.clear();
	      vlist << QVariant("int");
	      vlist << QVariant(m_paths[i]->sections());
	      vlist << QVariant(1);
	      vlist << QVariant(100);
	      plist["sections"] = vlist;

	      vlist.clear();
	      vlist << QVariant("combobox");
	      vlist << QVariant(m_paths[i]->capType());
	      vlist << QVariant("flat");
	      vlist << QVariant("round");
	      vlist << QVariant("arrow");
	      plist["cap style"] = vlist;

	      vlist.clear();
	      vlist << QVariant("combobox");
	      vlist << QVariant(m_paths[i]->arrowDirection());
	      vlist << QVariant("forward");
	      vlist << QVariant("backward");
	      plist["arrow direction"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_paths[i]->arrowForAll());
	      plist["arrows for all"] = vlist;

	      vlist.clear();
	      vlist << QVariant("checkbox");
	      vlist << QVariant(m_sameForAll);
	      plist["same for all"] = vlist;

	      vlist.clear();
	      plist["command"] = vlist;

	      vlist.clear();
	      QFile helpFile(":/pathgroups.help");
	      if (helpFile.open(QFile::ReadOnly))
		{
		  QTextStream in(&helpFile);
		  QString line = in.readLine();
		  while (!line.isNull())
		    {
		      if (line == "#begin")
			{
			  QString keyword = in.readLine();
			  QString helptext;
			  line = in.readLine();
			  while (!line.isNull())
			    {
			      helptext += line;
			      helptext += "\n";
			      line = in.readLine();
			      if (line == "#end") break;
			    }
			  vlist << keyword << helptext;
			}
		      line = in.readLine();
		    }
		}	      
	      plist["commandhelp"] = vlist;


	      vlist.clear();
	      QString mesg;
	      Vec s = m_paths[i]->shift();
	      mesg += QString("shift : %1 %2 %3\n").arg(s.x).arg(s.y).arg(s.z);
	      vlist << mesg;
	      plist["message"] = vlist;


	      QStringList keys;
	      keys << "color";
	      keys << "opacity";
	      keys << "gap";
	      keys << "smoothness";
	      keys << "sections";
	      keys << "gap";
	      keys << "cap style";
	      keys << "arrow direction";
	      keys << "arrows for all";
	      keys << "gap";
	      keys << "same for all";
	      keys << "command";
	      keys << "commandhelp";
	      keys << "message";
	      

	      propertyEditor.set("Path Group Parameters", plist, keys);

	      
	      QMap<QString, QPair<QVariant, bool> > vmap;

	      if (propertyEditor.exec() == QDialog::Accepted)
		vmap = propertyEditor.get();
	      else
		return true;
	      
	      keys = vmap.keys();

	      for(int ik=0; ik<keys.count(); ik++)
		{
		  QPair<QVariant, bool> pair = vmap.value(keys[ik]);


		  if (pair.second)
		    {
		      if (keys[ik] == "color")
			{
			  QColor color = pair.first.value<QColor>();
			  float r = color.redF();
			  float g = color.greenF();
			  float b = color.blueF();
			  pcolor = Vec(r,g,b);
			  m_paths[i]->setColor(pcolor);
			}
		      else if (keys[ik] == "opacity")
			m_paths[i]->setOpacity(pair.first.toDouble());
		      else if (keys[ik] == "sections")
			m_paths[i]->setSections(pair.first.toInt());
		      else if (keys[ik] == "smoothness")
			m_paths[i]->setSegments(pair.first.toInt());
		      else if (keys[ik] == "cap style")
			m_paths[i]->setCapType(pair.first.toInt());
		      else if (keys[ik] == "arrow direction")
			m_paths[i]->setArrowDirection(pair.first.toInt());
		      else if (keys[ik] == "arrows for all")
			m_paths[i]->setArrowForAll(pair.first.toBool());
		      else if (keys[ik] == "same for all")
			{
			  m_sameForAll = pair.first.toBool();
			  m_paths[i]->setSameForAll(m_sameForAll);
			}
		    }
		}

	      QString cmd = propertyEditor.getCommandString();
	      if (!cmd.isEmpty())
		processCommand(i, cmd);	
	      	      
	      updateGL();
	    }
	}
    }
  
  return true;
}

void
PathGroups::makePathConnections()
{
  for(int i=0; i<m_paths.count(); i++)
    m_paths[i]->disconnect();

  for(int i=0; i<m_paths.count(); i++)
    {
      connect(m_paths[i], SIGNAL(selectForEditing(int, int)),
	      this, SLOT(selectForEditing(int, int)));

      connect(m_paths[i], SIGNAL(deselectForEditing()),
	      this, SLOT(deselectForEditing()));
    }
}
void
PathGroups::deselectForEditing()
{
  for(int i=0; i<m_paths.count(); i++)
    m_paths[i]->setPointPressed(-1);
}

void
PathGroups::selectForEditing(int mouseButton,
			     int p0)
{
  int idx = -1;
  for(int i=0; i<m_paths.count(); i++)
    {
      if (m_paths[i]->grabsMouse())
	{
	  idx = i;
	  break;
	}
    }
  if (idx == -1)
    return;

  m_paths[idx]->setPointPressed(m_paths[idx]->pointPressed());
}

void
PathGroups::processCommand(int idx, QString cmd)
{
  bool ok;
  cmd = cmd.toLower();
  QStringList list = cmd.split(" ", QString::SkipEmptyParts);
  
  int li = 0;
  while (li < list.count())
    {
      if (list[li] == "disableundo")
	m_paths[idx]->disableUndo(true);
      else if (list[li] == "enableundo")
	m_paths[idx]->disableUndo(false);
      else if (list[li] == "shift")
	{
	  if (list.count()-li >= 3)
	    {
	      Vec v;
	      v.x = list[li+1].toFloat(&ok);
	      v.y = list[li+2].toFloat(&ok);
	      v.z = list[li+3].toFloat(&ok);
	      m_paths[idx]->setShift(v);
	      li += 3;
	    }
	  else
	    m_paths[idx]->setShift(Vec(0,0,0));
	}
      else if (list[li] == "normalize" ||
	  list[li] == "normalise")
	{
	  m_paths[idx]->normalize();
	}
      else if (list[li] == "setradius" || list[li] == "radius")
	{
	  if (list.count()-li >= 1)
	    {
	      float rad = list[li+1].toFloat(&ok);
	      m_paths[idx]->setRadX(0, rad, true);
	      m_paths[idx]->setRadY(0, rad, true);
	      li++;
	    }
	  else
	    QMessageBox::information(0, "PathGroup Command Error",
				     "No radius given");
	}
      else if (list[li] == "setrads" || list[li] == "rads")
	{
	  if (list.count()-li >= 1)
	    {
	      float radx = list[li+1].toFloat(&ok);
	      m_paths[idx]->setRadX(0, radx, true);
	      li++;
	    }
	  else
	    QMessageBox::information(0, "PathGroup Command Error",
				     "No S radius given");
	}
      else if (list[li] == "setradt" || list[li] == "radt")
	{
	  if (list.count()-li >= 1)
	    {
	      float rady = list[li+1].toFloat(&ok);
	      m_paths[idx]->setRadY(0, rady, true);
	      li++;
	    }
	  else
	    QMessageBox::information(0, "PathGroup Command Error",
				     "No T radius given");
	}
      else if (list[li] == "setangle" || list[li] == "angle")
	{
	  if (list.count()-li >= 1)
	    {
	      float a = list[li+1].toFloat(&ok);
	      m_paths[idx]->setAngle(0, a, true);
	      li++;
	    }
	  else
	    QMessageBox::information(0, "PathGroup Command Error",
				     "No angle given");
	}
      else
	QMessageBox::information(0, "PathGroup Command Error",
				 QString("Cannot understand the command : ") +
				 cmd);

      li++;
    }
}
